/*
 * @Author: 红尘痴子
 * @Date: 2020-06-29 17:27:54
 * @LastEditors: 红尘痴子
 * @LastEditTime: 2020-09-17 15:50:26
 * @Description:
 */

var dd = 0;
// 美妆说喵美美，正式 wxee9ad6e2b6603134
// 喵美美，测试 wx3b268c92f65ab19c
let api_url = '';
let accountInfo = wx.getAccountInfoSync();
let appid = accountInfo.miniProgram.appId; // 小程序 appId
/*
if (appid == 'wx3b268c92f65ab19c') {
	api_url = 'https://tapi.miaommei.com'; // 测试服务器地址
} else {
	api_url = 'https://abc.miaommei.com'; // 正式服务器地址
}
*/
api_url = 'http://127.0.0.1:8000'; // 测试服务器地址

const cmd5 = require('../utils/md5'); //md5加密
const util = require('../utils/util');
const screening = [
	'/user/index/getInfo',
	'/user/index/inviteCode',
	'/user/index/checkInviteCode',
	'/video/index/shareVideo',
	'/user/video/addWatchRecord',
	'/user/index/bindInviteCode',
	'createLive',
	'/user/branch/addWithdrawal',
]; //屏蔽错误提示名单
const http = (params) => {
	// console.log(params);
	let token = wx.getStorageSync('token');
	let key = 'kajsbkd123b55kwbdkj128y87';
	// 参数添加一个当前时间戳
	params.data.timestamp = Date.parse(new Date()) / 1000;
	let arr1 = params.data;
	let a = '';
	// 编码排序
	var arr = new Array();
	var num = 0;
	for (var i in arr1) {
		arr[num] = i;
		num++;
	}
	var sortArr = arr.sort();
	var sortObj = {};
	for (var i in sortArr) {
		sortObj[sortArr[i]] = arr1[sortArr[i]];
	}
	// console.log(sortObj, 'sortObj');
	// 拼接字符串
	for (var index in sortObj) {
		if (index != 'sign') {
			a += index + sortObj[index];
		}
		// console.log('key=', index, 'value=', sortObj[index]);
	}
	// console.log(a, '==================================');
	// console.log(api_url + params.url, '==================================');
	// 当前代码添加一个拼接后的参数
	params.data.sign = cmd5.md5(key + a + key);

	// console.log(params.data);
	return new Promise((resolve, reject) => {
		if (params.loading) {
			wx.showLoading({
				title: params.loading_title ? params.loading_title : '正在加载',
				mask: true,
			});
		}
		wx.request({
			url: api_url + params.url,
			data: params.data,
			method: params.method ? params.method : 'POST',
			header: params.header || {
				'Content-Type': 'application/x-www-form-urlencoded',
				Authorization: token,
				// Authorization: 'token1',
			},
			success: (res) => {
				// console.log(res);
				if (params.loading) {
					setTimeout(() => {
						wx.hideLoading();
					}, 800);
				}
				if (res.data.code == 200) {
					// http(params);
					if (params.url != '/user/login/wxLogin') {
						dd = 0;
					}
					resolve(res);

				} else if (res.data.code == 401) { // 调用授权
					console.log('调用授权---');
					getApp().store.setState({
						isAuthPhone: true
					});
					return ;
				} else if (res.data.code == 402) {
					if (dd < 3) {
						getToken(params).then(() => {
							http(params);
						});
					} else {
						wx.showToast({
							title: res.data.msg || res.data.data,
							icon: 'none',
						});
					}
				} else {
					reject(res);
					if (screening.indexOf(params.url) < 0) {
						util.showModal(res.data.msg || res.data.data || res)
						getApp().store.setState({
							isAuthPhone: false
						});
						// setTimeout(() => {
						// 	wx.showToast({
						// 		title:
						// 			res.data.msg ||
						// 			res.data.data ||
						// 			'No error message returned!',
						// 		icon: 'none',
						// 	});
						// }, 1200);
					}
				}
			},
			fail: (err) => {
				util.showModal(err)
				// console.log(err);
				// if (dd < 3) {
				// 	postFail(params).then(() => {
				// 		http(params);
				// 	});
				// } else {
				// 	wx.showToast({
				// 		title: '接口出错,请稍后再试!',
				// 		icon: 'none',
				// 	});
				// }
				reject('err---',err);
			},
		});
	});
};
// 接口报错后,重新请求三次
const postFail = (params) => {
	return new Promise((resolve, reject) => {
		dd = dd + 1;
		resolve(params);
	});
};
// 重新获取token,并请求当前报错的接口
const getToken = (params) => {
	return new Promise((resolve, reject) => {
		wx.login({
			success(res) {
				if (res.code) {
					http({
						url: '/user/login/wxLogin',
						data: {
							code: res.code,
						},
						header: {},
					})
						.then((res) => {
							dd = dd + 1;
							getApp().store.setState({
								infoData: res.data.data,
								token: res.data.data.token,
							});
							wx.setStorageSync('infoData', res.data.data);
							wx.setStorageSync('token', res.data.data.token);
							resolve(params);
						})
						.catch((err) => {});
				}
			},
			fail: (err) => {},
		});
	});
};
module.exports = {
	http,
	api_url,
};
